//
//  MeViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/30.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "MeViewController.h"
#import "MainNavigationController.h"
#import "JKAccountManager.h"
#import "JKProgressHUD.h"

@interface MeViewController () <UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *IconButton;
@property (weak, nonatomic) IBOutlet UIButton *logoutButton;
@property (weak, nonatomic) IBOutlet UIButton *changeNameButton;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@end

@implementation MeViewController

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:JKUserNameKey];
    self.nameLabel.text = userName;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView removeFromSuperview];
    self.navBarView.title = @"个人主页";
    
    __weak typeof(self) weakSelf = self;
    [self.navBarView setBackBtnClickBlock:^(UIButton *btn) {
        MainNavigationController *mainNav = (MainNavigationController *)weakSelf.navigationController;
        !mainNav.backBtnBlock ? : mainNav.backBtnBlock();
    }];
    
    self.logoutButton.layer.borderColor = [[UIColor blackColor] colorWithAlphaComponent:0.3].CGColor;
    self.logoutButton.layer.borderWidth = 1;
    
    self.textView.delegate = self;
    
   NSString *imgPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"userIcon.png"];
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
    if (img == nil) {
        img = [UIImage imageNamed:@"myIcon"];
    }
    
    [self.IconButton setImage:[img circleImageWithBorderColor:JKColor(57, 150, 118) borderWidth:5] forState:(UIControlStateNormal)];
    [self.IconButton setImage:[img circleImageWithBorderColor:JKMainColor borderWidth:5] forState:(UIControlStateHighlighted)];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return NO;
}

#pragma mark - 事件处理
- (IBAction)changeNameButtonClick:(UIButton *)sender {
    sender.hidden = YES;
    self.textView.hidden = !sender.hidden;
    self.textView.text = self.nameLabel.text;
    [self.textView becomeFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (!self.changeNameButton.hidden) return;
    [self saveName];
}

- (void)saveName{
    [self.view endEditing:YES];
    self.changeNameButton.hidden = NO;
    self.nameLabel.text = self.textView.text;
    
    [[NSUserDefaults standardUserDefaults] setObject:self.textView.text forKey:JKUserNameKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    self.textView.text = nil;
    self.textView.hidden = YES;
    
    [[NSUserDefaults standardUserDefaults] setObject:self.nameLabel.text forKey:JKUserNameKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (IBAction)IconButtonClick:(id)sender {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *actionTakePhoto = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self updateIconWithSourType:(UIImagePickerControllerSourceTypeCamera)];
    }];
    
    UIAlertAction *actionSelectPhoto = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self updateIconWithSourType:(UIImagePickerControllerSourceTypePhotoLibrary)];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alertVc addAction:actionTakePhoto];
    [alertVc addAction:actionSelectPhoto];
    [alertVc addAction:actionCancel];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVc animated:YES completion:nil];
}

- (IBAction)logoutButtonCilck:(id)sender {
    [JKAccountManager logout];
    
    if (self.isSettingIn) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        if ([self.delegate respondsToSelector:@selector(meViewControllerDidClickLogout:)]) {
            [self.delegate meViewControllerDidClickLogout:self];
        }
    }
    
    [JKProgressHUD showSuccessWithStatus:@"退出成功！"];
}

- (void)updateIconWithSourType:(UIImagePickerControllerSourceType)sourceType{
    
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) return;
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = sourceType;
    imagePicker.allowsEditing = YES;
    
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    UIImage *newImg = [image circleImage];
    
    NSData *newImgData = UIImagePNGRepresentation(newImg);
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"userIcon.png"];
    [newImgData writeToFile:filePath atomically:YES];
    
    UIImage *newImgNormal = [newImg circleImageWithBorderColor:JKColor(57, 150, 118) borderWidth:5];
    UIImage *newImgHighlighted = [newImg circleImageWithBorderColor:JKMainColor borderWidth:5];
    
    [self.IconButton setImage:newImgNormal forState:(UIControlStateNormal)];
    [self.IconButton setImage:newImgHighlighted forState:(UIControlStateHighlighted)];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - <UITextViewDelegate>
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]) {
        
        [self saveName];
        return NO;
    }
    
    return YES;
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        self.nameLabel.textColor = JKColor(186, 186, 186);
        [self.logoutButton setBackgroundImage:[UIImage imageNamed:@"logout_night_normal.png"] forState:(UIControlStateNormal)];
        [self.logoutButton setBackgroundImage:[UIImage imageNamed:@"logout_night_highlighted.png"] forState:(UIControlStateHighlighted)];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
        [self.logoutButton setBackgroundImage:[UIImage imageNamed:@"logout_day_normal.png"] forState:(UIControlStateNormal)];
        [self.logoutButton setBackgroundImage:[UIImage imageNamed:@"logout_day_highlighted.png"] forState:(UIControlStateHighlighted)];
        self.nameLabel.textColor = [UIColor blackColor];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
